from ._base import BaseModel
from .tag import Tag, association_table
from ..extends.flask_sqlalchemy import db
from flask import url_for
from flask_login import current_user


class BanWords(BaseModel):
    ban_word = db.Column(db.String(32), unique=True, comment='违禁词')


class Article(BaseModel):
    title = db.Column(db.String(64), comment='标题', index=True, nullable=False)
    original_title = db.Column(db.String(64), comment='原标题', nullable=False, default='')
    source = db.Column(db.String(16), comment='来源', index=True, nullable=False, default='')
    author = db.Column(db.String(16), comment='作者', index=True, nullable=False, default='')
    keyword = db.Column(db.String(64), comment='关键词', index=True, nullable=False, default='')
    hot = db.Column(db.Integer, comment='阅读量', index=True, nullable=False, default=100)
    top = db.Column(db.SmallInteger, index=True, nullable=False, default=0, comment='头条')
    good = db.Column(db.SmallInteger, index=True, nullable=False, default=0, comment='推荐')
    focus = db.Column(db.SmallInteger, index=True, nullable=False, default=0, comment='焦点图')
    description = db.Column(db.String(128), comment='描述', nullable=False, default='')
    thumbnail = db.Column(db.String(200), comment='缩略图', nullable=False, default='')
    is_member = db.Column(db.Boolean, nullable=False, default=False, comment='前台or后台发布')

    category_id = db.Column(db.Integer, nullable=False, comment='栏目')
    publisher_id = db.Column(db.Integer, nullable=False, default=0, comment='发布人')
    checker_id = db.Column(db.Integer, nullable=False, default=0, comment='审核人')

    body = db.relationship(
        'Body',
        uselist=False,
        foreign_keys="Body.article_id",
        primaryjoin="Article.id == Body.article_id"
    )
    publisher = db.relationship(
        'User',
        foreign_keys="Article.publisher_id",
        primaryjoin="Article.publisher_id == User.id",
        uselist=False
    )
    checker = db.relationship(
        'User',
        foreign_keys="Article.checker_id",
        primaryjoin="Article.checker_id == User.id",
        uselist=False
    )

    category = db.relationship(
        'Category',
        foreign_keys="Article.category_id",
        primaryjoin="Article.category_id == Category.id",
        uselist=False
    )

    tag = db.relationship(
        'Tag',
        secondary=association_table,
        back_populates='article'
    )

    @property
    def has_thumb(self):
        return self.query.filter(Article.thumbnail != '')

    @property
    def thumb_url(self):
        return self.thumbnail if self.thumbnail else url_for('static', filename='default.jpg')

    @property
    def url(self):
        return url_for('home.article_select', article_id=self.id, _external=True)

    @property
    def status_text(self):
        return '已发布' if self.status else '待审核'

    @property
    def tags_str(self):
        return '，'.join(_t.tag_name for _t in self.tag)

    @classmethod
    def admins_add(cls, fields):
        with db.auto_commit():
            this = cls()
            this.set_fields(fields)
            this.body = Body(content=fields.get('content'))
            this.publisher_id = current_user.id
            this.checker_id = current_user.id
            this.is_member = 0
            db.session.add(this)
            # 插入tags
            this._insert_tags(fields['tags'].split('，') if fields['tags'] else [])
        return this

    def update(self, fields):
        with db.auto_commit():
            self.set_fields(fields)
            self.status = True
            self.body.content = fields.get('content')
            _post_tags = fields['tags'].split('，') if fields['tags'] else []
            for _tag in self.tag[:]:
                """
                    修改当前文章的时候对应关联标签的处理
                    如果当前文章关联的标签中 已经存在于_post_tags中
                    则将 _post_tags中对应的标签数据清除掉，已保证文章和标签关联的数据标唯一性
                    如果当前文章关联的标签中 不存在于_post_tag中
                    则将 当前文章与当前标签对应的关联关系接触
                """
                if _tag.tag_name in _post_tags:
                    _post_tags.remove(_tag.tag_name)
                else:
                    _tag.num = _tag.num - 1 if _tag.num else 0
                    self.tag.remove(_tag)

            # 重新插入标签关联
            self._insert_tags(_post_tags)
        return self

    def _insert_tags(self, tags):
        # 处理Tags
        for _t in tags:
            tag = Tag.query.filter_by(tag_name=_t).first()
            if not tag:
                # 不存在的标签 则写入
                tag = Tag()
                tag.tag_name = _t
                tag.num = 0
                # 随机获取一个栏目
                # tc = TagCategory.query.order_by(func.rand()).first()
                # tag.tag_category = tc.id
                db.session.add(tag)
            # 文章标签关联
            tag.num = tag.num + 1
            self.tag.append(tag)

    @property
    def previous(self):
        # 上一篇
        return db.session.query(Article).filter(
            Article.category_id == self.category_id,
            Article.id < self.id
        ).order_by(Article.id.desc()).first()

    @property
    def next(self):
        # 下一篇
        return db.session.query(Article).filter(
            Article.category_id == self.category_id,
            Article.id > self.id
        ).first()

    def hot_plus(self, number=1):
        # 文章hot增加
        self.hot = self.hot + number
        db.session.commit()


class Body(db.Model):
    __tablename__ = 'article_data'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    content = db.Column(db.Text, comment='内容')
    article_id = db.Column(db.Integer, unique=True, nullable=False, comment='文章id')
